﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;

namespace nextwaver.SelfLearning.Controls
{
    public partial class Course : Form
    {
        public Course()
        {
            InitializeComponent();
        }

        #region fields
        ConnectServer.cConection Conn = new ConnectServer.cConection();
        private TreeNode tnRoot = new TreeNode();
        private string ticketID;
        DataRow drCurrent;
        private string fileStr;
        private string fileType;
        private string ipAddr;
        private string studentName;
        private int _ServerTime;
        private int _EndTimeWithSec;
        private int _1stAlert;
        private int _2ndAlert;

        private int _1stAlertInSec;
        private int _2ndAlertInSec;

        #endregion

        #region property

        public string TicketID
        {
            get { return VDOStatus.TicketID; }
        }

        public string StudentName
        {
            get { return VDOStatus.MemberName; }
            set { studentName = value; }
        }

        public string IpAddr
        {
            get { return ipAddr; }
            set { ipAddr = value; }
        }

        #endregion

        private void DrawNode()
        {
            string sql = @"SELECT b.TypeCourse
                  FROM [dbo].[Fact_LearningTicket] as a,
                  [dbo].[Dim_Courses] as b
                  where TicketID = '@TicketID'
                  and a.CourseID = b.CourseID";
            sql = sql.Replace("@TicketID", TicketID);
            DataSet dsRoot = Conn.Retreive(sql, Conn.Conn);
            treeView1.Nodes.Clear();
            tnRoot.Text = "All Courses Available";
            tnRoot.Name = "rootNode";
            tnRoot.Expand();
            treeView1.Nodes.Add(tnRoot);
            foreach (DataRow dr in dsRoot.Tables[0].Rows)
            {
                TreeNode tnParent = new TreeNode();
                tnParent.Text = dr[0].ToString().Trim();
                tnParent.Name = dr[0].ToString().Trim();
                tnParent.Expand();
                tnRoot.Nodes.Add(tnParent);
                DrawChildNode(tnParent, tnParent.Name);
            }
            treeView1.ExpandAll();

        }

        private void DrawChildNode(TreeNode parent, string ParentId)
        {
            string sql = @"SELECT b.CourseName
                      FROM [dbo].[Fact_LearningTicket] as a,
                      [dbo].[Dim_Courses] as b
                      where TicketID = '@TicketID'
                      and a.CourseID = b.CourseID";
            sql = sql.Replace("@TicketID", TicketID);
            DataSet dsChild = Conn.Retreive(sql, Conn.Conn);
            foreach (DataRow dr in dsChild.Tables[0].Rows)
            {
                TreeNode child = new TreeNode();
                child.Text = dr[0].ToString().Trim();
                child.Name = dr[0].ToString().Trim();
                child.Collapse();
                parent.Nodes.Add(child);
            }
        }

        public string RandomString(int size)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            string ch;
            for (int i = 0; i < size; i++)
            {
                int s = random.Next(0, 1);
                switch (s)
                {
                    case 0: ch = "" + Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                        builder.Append(ch);
                        break;
                    case 1: ch = random.Next(1, 9).ToString();
                        builder.Append(ch);
                        break;
                }
            }
            return builder.ToString().ToUpper();
        }

        private void setUsing()
        {
            try
            {
                string sql = @"UPDATE [dbo].[Dim_Station]
                        SET [TicketID] = '@TicketID', [StudentName]='@StudentName'
                        WHERE [IPAddress]='@IPAddr'";
                sql = sql.Replace("@TicketID", TicketID);
                sql = sql.Replace("@StudentName", StudentName);
                sql = sql.Replace("@IPAddr", IpAddr);
                Conn.Execute(sql, Conn.Conn);

                sql = @" UPDATE [dbo].[Fact_LearningTicket]
                        SET [StateTicket]='Using'
                        WHERE [TicketID] = '@TicketID'";
                sql = sql.Replace("@TicketID", TicketID);
                Conn.Execute(sql, Conn.Conn);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void setTicketUsed()
        {
            try
            {
                string sql = @" UPDATE [dbo].[Fact_LearningTicket]
                        SET [StateTicket]='Use'
                        WHERE [TicketID] = '@TicketID'";
                sql = sql.Replace("@TicketID", TicketID);
                Conn.Execute(sql, Conn.Conn);

                sql = @"UPDATE [dbo].[Dim_Station]
                        SET [TicketID] = '', [StudentName]=''
                        WHERE [IPAddress]='@IPAddr'";
                sql = sql.Replace("@IPAddr", IpAddr);
                Conn.Execute(sql, Conn.Conn);
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }

        private void Course_Load(object sender, EventArgs e)
        {
            setUsing();
            DrawNode();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            e.Node.Expand();

            string strLiveCheck = @"SELECT LearningType FROM [dbo].[Fact_LearningTicket] WHERE TicketID = '@Ticket'";
            strLiveCheck = strLiveCheck.Replace("@Ticket",TicketID);
            DataSet dsLive = Conn.Retreive(strLiveCheck, Conn.Conn);
            //ClearLabelValue();
            //string pNode = e.Node.Parent.Text;
            //string nSelf = e.Node.Text;
            DataSet ds;
            string sqlC0s = "";
            if (dsLive.Tables[0].Rows[0]["LearningType"].ToString() == "Live")
            {
                sqlC0s = "EXECUTE [dbo].[sp_Get_LiveCoursesDetials] '" + TicketID + "'";
            }
            else
            {
                sqlC0s = "EXECUTE [dbo].[sp_Get_CoursesDetials] '" + TicketID + "'";
            }
            Console.WriteLine(sqlC0s);
            ds = Conn.Retreive(sqlC0s, Conn.Conn);
            //DataSet ds = RunQuery("");
            //string qSql = "EXECUTE [dbo].[sp_Get_CoursesFromName] '" + pNode + "','" + nSelf + "','" + TicketID + "'";
            //DataSet ds = Conn.Retreive(qSql, Conn.con);
            if (ds == null)
            {
                Model.CommonLibrary.MessageBoxDialog(nextwaver.SelfLearning.Model.CommonLibrary.DialogType.NoCourse);
            }
            else
            {
                dgvCourse.DataSource = ds.Tables[0].DefaultView;

                GridViewUtils gConf = new GridViewUtils();
                gConf.SetParameterColumn("TicketID", "", false);
                gConf.SetParameterColumn("MemberName","",false);
                gConf.SetParameterColumn("TypeCourse", "ประเภทคอร์ส", true);
                gConf.SetParameterColumn("CourseName", "ชื่อคอร์ส", true);
                gConf.SetParameterColumn("LectureName", "ครั้งที่", true);
                gConf.SetParameterColumn("Description", "รายละเอียด", true);
                gConf.SetParameterColumn("UseTime", "เวลาที่ใช้", true);
                gConf.SetParameterColumn("Length", "เวลาเรียนทั้งหมด", false);
                gConf.SetParameterColumn("SaleDate", "วันที่ซื้อ", false);
                gConf.SetParameterColumn("EndTimeCourseBuy", "วันหมดอายุ", false);
                gConf.SetParameterColumn("VdoName", "", false);
                gConf.SetParameterColumn("TypeFile", "", false);
                gConf.SetParameterColumn("BalanceTime", "", false);
                gConf.SetParameterColumn("AllTime", "", false);
                gConf.GridViewRanderConfig(dgvCourse);
            }
        }

        private void dgvCourse_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            Console.WriteLine(e.RowIndex);
            DataRowView drv = (DataRowView)dgvCourse.CurrentRow.DataBoundItem;
            drCurrent = drv.Row;
            setLabelValue(drCurrent);
        }
        private void setLabelValue(DataRow row)
        {
            string a = row.ToString();
            string studentName = row["MemberName"].ToString();
            //lbl1.Text = row["TypeCourse"].ToString();
            //lbl2.Text = row["CourseName"].ToString();
            //lbl3.Text = row["LectureName"].ToString();
            //lbl4.Text = row["Description"].ToString();
            //lbl5.Text = row["Length"].ToString();//เวลาทั้งหมด
            //lbl6.Text = row["UseTime"].ToString();//เวลาที่ใช้
            ////lbl6.Text = SELF.Model.Leaning.Int2TimeWithSec(GetRoundTime() * 60).ToString();
            //lbl7.Text = row["SaleDate"].ToString();//วันที่ซื้อ
            //lbl8.Text = row["EndTimeCourseBuy"].ToString();//เรียนได้ถึง
            fileStr = row["VdoName"].ToString();
            fileType = row["TypeFile"].ToString();

        }
        Process proc = new Process();
        Thread thPlayer;
        /// <summary>
        /// Enter course
        /// </summary>
        private void panel1_Click(object sender, EventArgs e)
        {
            DialogResult confirm = MessageBox.Show(this, "ต้องการเข้าเรียนหรือไม่", "ยืนยัน", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (confirm == DialogResult.Yes)
            {
                string fileName = cGobal.streamServer + cGobal.GetCourseID(fileStr) + "/" + fileStr + fileType;
                thPlayer = new Thread(new ParameterizedThreadStart(StartPlayer));
                thPlayer.Start(fileName);
            }
        }
        private void StartPlayer(object fname)
        {
            proc.StartInfo.FileName = Application.StartupPath + "\\WMPlayer\\WinPlayer.exe";
            string name = fname.ToString();
            proc.StartInfo.Arguments = name;
            proc.Start();
            proc.WaitForExit();
            //this.Invoke((MethodInvoker)delegate
            //{
            //    SetHistoryEnd();
            //});
            //SetHistoryEnd();
            //CalcUsageTime();

        }

    }
}
